using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.Text.Json;
using System.Text.RegularExpressions;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 人物角色规划引擎 - 智能角色生成、关系网络、发展轨迹规划
    /// </summary>
    public class CharacterPlanningEngine
    {
        private readonly ILogger<CharacterPlanningEngine> _logger;
        private readonly IAIService _aiService;
        private readonly IProjectService _projectService;
        private readonly IDataStorageService _dataStorage;
        private readonly CharacterRelationshipAnalyzer _relationshipAnalyzer;
        private readonly CharacterDevelopmentPlanner _developmentPlanner;

        public CharacterPlanningEngine(
            ILogger<CharacterPlanningEngine> logger,
            IAIService aiService,
            IProjectService projectService,
            IDataStorageService dataStorage,
            CharacterRelationshipAnalyzer relationshipAnalyzer,
            CharacterDevelopmentPlanner developmentPlanner)
        {
            _logger = logger;
            _aiService = aiService;
            _projectService = projectService;
            _dataStorage = dataStorage;
            _relationshipAnalyzer = relationshipAnalyzer;
            _developmentPlanner = developmentPlanner;
        }

        /// <summary>
        /// 根据用户意图生成角色规划
        /// </summary>
        public async Task<CharacterPlan> GenerateCharacterPlanAsync(EnhancedUserIntent intent)
        {
            try
            {
                _logger.LogInformation("开始生成角色规划");

                var plan = new CharacterPlan
                {
                    CreatedAt = DateTime.Now,
                    Strategy = await DetermineCharacterPlanningStrategyAsync(intent)
                };

                // 根据意图类型执行不同的规划策略
                var complexIntent = intent.ComplexIntent as ComplexIntent;
                CharacterPlanningIntent? characterIntent = null;
                if (complexIntent?.SpecializedIntents.TryGetValue("CharacterPlanning", out var characterIntentObj) == true)
                {
                    characterIntent = (CharacterPlanningIntent)characterIntentObj;
                }

                // 当未识别到专门的角色规划意图，但上层要求进行角色规划时，构造一个合理的默认意图，避免产出为空
                if (characterIntent == null && intent.RequiresCharacterPlanning)
                {
                    characterIntent = new CharacterPlanningIntent
                    {
                        DetectedAt = DateTime.Now,
                        Confidence = 0.5,
                        PlanningType = CharacterPlanningType.General,
                        PlanningScope = CharacterPlanningScope.Major,
                        RequiredAttributes = new List<string> { "姓名", "背景", "性格", "目标", "冲突" }
                    };
                    _logger.LogInformation("未检测到显式角色规划意图，已启用默认的通用角色规划");
                }

                if (characterIntent != null)
                {
                    switch (characterIntent.PlanningType)
                    {
                        case CharacterPlanningType.Creation:
                            await PlanCharacterCreationAsync(plan, intent, characterIntent);
                            break;
                        case CharacterPlanningType.Relationship:
                            await PlanCharacterRelationshipsAsync(plan, intent, characterIntent);
                            break;
                        case CharacterPlanningType.Development:
                            await PlanCharacterDevelopmentAsync(plan, intent, characterIntent);
                            break;
                        case CharacterPlanningType.Analysis:
                            await PlanCharacterAnalysisAsync(plan, intent, characterIntent);
                            break;
                        default:
                            await PlanGeneralCharacterWorkAsync(plan, intent, characterIntent);
                            break;
                    }
                }
                else
                {
                    _logger.LogWarning("未触发任何角色规划分支，结果可能为空");
                }

                _logger.LogInformation($"角色规划生成完成，包含 {plan.Characters.Count} 个角色");
                return plan;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成角色规划失败");
                throw;
            }
        }

        /// <summary>
        /// 执行角色规划
        /// </summary>
        public async Task<CharacterExecutionResult> ExecutePlanAsync(CharacterPlan plan, Models.ExecutionContext context)
        {
            try
            {
                _logger.LogInformation($"开始执行角色规划: {plan.Id}");

                var result = new CharacterExecutionResult();

                // 按优先级执行角色创建
                var sortedCharacters = plan.Characters.OrderBy(c => c.Importance).ToList();

                foreach (var plannedCharacter in sortedCharacters)
                {
                    var character = await CreateCharacterFromPlanAsync(plannedCharacter, context);
                    if (character != null)
                    {
                        result.CreatedCharacters.Add(character);
                    }
                }

                // 建立角色关系
                await EstablishCharacterRelationshipsAsync(plan.Relationships, result.CreatedCharacters, context);

                // 设置角色发展轨迹
                await SetupCharacterDevelopmentPathsAsync(plan.DevelopmentPaths, result.CreatedCharacters, context);

                // 收集执行指标
                result.Metrics["TotalCharacters"] = result.CreatedCharacters.Count;
                result.Metrics["RelationshipsEstablished"] = plan.Relationships.Count;
                result.Metrics["DevelopmentPaths"] = plan.DevelopmentPaths.Count;

                _logger.LogInformation($"角色规划执行完成，创建了 {result.CreatedCharacters.Count} 个角色");
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "执行角色规划失败");
                throw;
            }
        }

        /// <summary>
        /// 确定角色规划策略
        /// </summary>
        private async Task<CharacterPlanningStrategy> DetermineCharacterPlanningStrategyAsync(EnhancedUserIntent intent)
        {
            var strategy = new CharacterPlanningStrategy
            {
                Name = "智能角色规划策略",
                Description = "基于用户意图和项目上下文的智能角色规划"
            };

            // 根据项目类型调整策略
            if (intent.ProjectContext?.ProjectType == "Novel")
            {
                strategy.Parameters["FocusOnStoryDriven"] = true;
                strategy.Parameters["EnableCharacterArcs"] = true;
                strategy.Parameters["MaxMainCharacters"] = 5;
                strategy.Parameters["MaxSupportingCharacters"] = 15;
            }
            else
            {
                strategy.Parameters["FocusOnFunctional"] = true;
                strategy.Parameters["EnableRoleBasedDesign"] = true;
            }

            return strategy;
        }

        /// <summary>
        /// 规划角色创建
        /// </summary>
        private async Task PlanCharacterCreationAsync(CharacterPlan plan, EnhancedUserIntent intent, CharacterPlanningIntent characterIntent)
        {
            var creationPrompt = BuildCharacterCreationPrompt(intent, characterIntent);
            var aiResponse = await _aiService.GenerateTextAsync(creationPrompt, 3000, 0.8f);

            var characters = await ParseCharacterCreationResponseAsync(aiResponse, characterIntent);

            // 若AI返回为空或解析失败，使用默认基线角色，避免空结果
            if (characters == null || characters.Count == 0)
            {
                _logger.LogWarning("角色创建解析为空，使用默认基线角色");
                characters = CreateBaselineCharacters(intent, 3);
            }

            plan.Characters.AddRange(characters);

            // 自动生成基础关系网络
            if (characters.Count > 1)
            {
                var relationships = await _relationshipAnalyzer.GenerateBasicRelationshipsAsync(characters);
                plan.Relationships.AddRange(relationships);
            }
        }

        /// <summary>
        /// 规划角色关系
        /// </summary>
        private async Task PlanCharacterRelationshipsAsync(CharacterPlan plan, EnhancedUserIntent intent, CharacterPlanningIntent characterIntent)
        {
            // 获取现有角色
            var existingCharacters = await GetExistingCharactersAsync(intent.ProjectContext);

            // 分析和规划关系网络
            var relationships = await _relationshipAnalyzer.AnalyzeAndPlanRelationshipsAsync(
                existingCharacters, characterIntent.TargetCharacters);

            plan.Relationships.AddRange(relationships);
        }

        /// <summary>
        /// 规划角色发展
        /// </summary>
        private async Task PlanCharacterDevelopmentAsync(CharacterPlan plan, EnhancedUserIntent intent, CharacterPlanningIntent characterIntent)
        {
            var existingCharacters = await GetExistingCharactersAsync(intent.ProjectContext);

            foreach (var characterName in characterIntent.TargetCharacters)
            {
                var character = existingCharacters.FirstOrDefault(c => c.Name == characterName);
                if (character != null)
                {
                    var developmentPath = await _developmentPlanner.PlanCharacterDevelopmentAsync(character, intent);
                    plan.DevelopmentPaths.Add(developmentPath);
                }
            }
        }

        /// <summary>
        /// 规划角色分析
        /// </summary>
        private async Task PlanCharacterAnalysisAsync(CharacterPlan plan, EnhancedUserIntent intent, CharacterPlanningIntent characterIntent)
        {
            // 创建分析任务而不是直接创建角色
            var analysisCharacter = new PlannedCharacter
            {
                Name = "角色分析任务",
                Type = CharacterType.Background,
                Description = "对现有角色进行深度分析",
                Importance = CharacterImportance.Tertiary
            };

            plan.Characters.Add(analysisCharacter);
        }

        /// <summary>
        /// 规划通用角色工作
        /// </summary>
        private async Task PlanGeneralCharacterWorkAsync(CharacterPlan plan, EnhancedUserIntent intent, CharacterPlanningIntent characterIntent)
        {
            // 根据用户输入的通用需求进行规划
            var generalPrompt = $@"根据用户需求规划角色相关工作：

用户需求：{intent.OriginalRequest}
项目类型：{intent.ProjectContext?.ProjectType ?? "未知"}

请提供角色规划建议：";

            var aiResponse = await _aiService.GenerateTextAsync(generalPrompt, 2000, 0.7f);

            if (string.IsNullOrWhiteSpace(aiResponse))
            {
                _logger.LogWarning("通用角色规划AI响应为空，使用默认基线角色");
                plan.Characters.AddRange(CreateBaselineCharacters(intent, 3));
                return;
            }

            // 解析AI响应并创建相应的规划
            await ParseGeneralPlanningResponseAsync(plan, aiResponse, characterIntent);

            // 若解析后仍无角色，使用默认基线角色兜底
            if (!plan.Characters.Any())
            {
                _logger.LogWarning("通用角色规划解析后仍为空，使用默认基线角色");
                plan.Characters.AddRange(CreateBaselineCharacters(intent, 3));
            }
        }

        /// <summary>
        /// 构建角色创建提示
        /// </summary>
        private string BuildCharacterCreationPrompt(EnhancedUserIntent intent, CharacterPlanningIntent characterIntent)
        {
            var prompt = $@"请根据以下信息创建角色：

用户需求：{intent.OriginalRequest}
项目类型：{intent.ProjectContext?.ProjectType ?? "通用"}
规划范围：{characterIntent.PlanningScope}
所需属性：{string.Join(", ", characterIntent.RequiredAttributes)}

请为每个角色提供以下信息：
1. 角色名称
2. 角色类型（主角/配角/反派/龙套）
3. 角色描述
4. 主要属性
5. 技能列表
6. 装备列表
7. 重要程度

请以JSON格式返回角色列表：";

            return prompt;
        }

        /// <summary>
        /// 解析角色创建响应
        /// </summary>
        private async Task<List<PlannedCharacter>> ParseCharacterCreationResponseAsync(string aiResponse, CharacterPlanningIntent intent)
        {
            var characters = new List<PlannedCharacter>();

            try
            {
                // 尝试解析JSON格式的响应
                var jsonResponse = JsonSerializer.Deserialize<List<Dictionary<string, object>>>(aiResponse);

                foreach (var characterData in jsonResponse)
                {
                    var character = new PlannedCharacter
                    {
                        Name = characterData.GetValueOrDefault("name", "未命名角色").ToString(),
                        Description = characterData.GetValueOrDefault("description", "").ToString(),
                        Type = ParseCharacterType(characterData.GetValueOrDefault("type", "Supporting").ToString()),
                        Importance = ParseCharacterImportance(characterData.GetValueOrDefault("importance", "Secondary").ToString())
                    };

                    // 解析属性
                    if (characterData.TryGetValue("attributes", out var attributesObj))
                    {
                        character.Attributes = JsonSerializer.Deserialize<Dictionary<string, object>>(attributesObj.ToString());
                    }

                    // 解析技能
                    if (characterData.TryGetValue("skills", out var skillsObj))
                    {
                        character.Skills = JsonSerializer.Deserialize<List<string>>(skillsObj.ToString());
                    }

                    // 解析装备
                    if (characterData.TryGetValue("equipment", out var equipmentObj))
                    {
                        character.Equipment = JsonSerializer.Deserialize<List<string>>(equipmentObj.ToString());
                    }

                    characters.Add(character);
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "解析AI响应失败，使用备用解析方法");
                // 备用解析方法
                characters = await ParseCharacterCreationResponseFallbackAsync(aiResponse);
            }

            return characters;
        }

        /// <summary>
        /// 备用角色创建响应解析
        /// </summary>
        private async Task<List<PlannedCharacter>> ParseCharacterCreationResponseFallbackAsync(string aiResponse)
        {
            var characters = new List<PlannedCharacter>();

            // 简单的文本解析逻辑
            var lines = aiResponse.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            PlannedCharacter currentCharacter = null;

            foreach (var line in lines)
            {
                if (line.Contains("角色名") || line.Contains("名称"))
                {
                    if (currentCharacter != null)
                    {
                        characters.Add(currentCharacter);
                    }
                    currentCharacter = new PlannedCharacter
                    {
                        Name = ExtractValue(line),
                        Type = CharacterType.Supporting,
                        Importance = CharacterImportance.Secondary
                    };
                }
                else if (currentCharacter != null)
                {
                    if (line.Contains("描述"))
                    {
                        currentCharacter.Description = ExtractValue(line);
                    }
                    else if (line.Contains("类型"))
                    {
                        currentCharacter.Type = ParseCharacterType(ExtractValue(line));
                    }
                }
            }

            if (currentCharacter != null)
            {
                characters.Add(currentCharacter);
            }

            return characters;
        }

        /// <summary>
        /// 从文本行中提取值
        /// </summary>
        private string ExtractValue(string line)
        {
            var colonIndex = line.IndexOf('：');
            if (colonIndex == -1) colonIndex = line.IndexOf(':');

            return colonIndex >= 0 ? line.Substring(colonIndex + 1).Trim() : line.Trim();
        }

        /// <summary>
        /// 解析角色类型
        /// </summary>
        private CharacterType ParseCharacterType(string typeString)
        {
            return typeString.ToLower() switch
            {
                "主角" or "protagonist" => CharacterType.Protagonist,
                "反派" or "antagonist" => CharacterType.Antagonist,
                "配角" or "supporting" => CharacterType.Supporting,
                "龙套" or "background" => CharacterType.Background,
                _ => CharacterType.Supporting
            };
        }

        /// <summary>
        /// 解析角色重要程度
        /// </summary>
        private CharacterImportance ParseCharacterImportance(string importanceString)
        {
            return importanceString.ToLower() switch
            {
                "主要" or "primary" => CharacterImportance.Primary,
                "次要" or "secondary" => CharacterImportance.Secondary,
                "三级" or "tertiary" => CharacterImportance.Tertiary,
                "背景" or "background" => CharacterImportance.Background,
                _ => CharacterImportance.Secondary
            };
        }

        /// <summary>
        /// 获取现有角色
        /// </summary>
        private async Task<List<Character>> GetExistingCharactersAsync(ProjectContext? projectContext)
        {
            if (projectContext?.ProjectId == null)
                return new List<Character>();

            try
            {
                // 这里应该调用实际的数据服务获取角色
                // 暂时返回空列表
                return new List<Character>();
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "获取现有角色失败");
                return new List<Character>();
            }
        }

        /// <summary>
        /// 从规划创建实际角色
        /// </summary>
        private async Task<Character?> CreateCharacterFromPlanAsync(PlannedCharacter plannedCharacter, Models.ExecutionContext context)
        {
            try
            {
                _logger.LogInformation($"开始创建角色: {plannedCharacter.Name}");

                // 使用AI生成详细的角色信息
                var detailedCharacter = await GenerateDetailedCharacterAsync(plannedCharacter, context);

                var character = new Character
                {
                    Name = detailedCharacter.Name,
                    Description = detailedCharacter.Description,
                    Attributes = JsonSerializer.Serialize(detailedCharacter.Attributes),
                    Skills = JsonSerializer.Serialize(detailedCharacter.Skills),
                    Equipment = JsonSerializer.Serialize(detailedCharacter.Equipment)
                };

                // 保存角色到数据服务
                try
                {
                    // 暂时跳过保存，因为SaveCharacterAsync方法可能不存在
                    // await _dataStorage.SaveCharacterAsync(character);
                    _logger.LogInformation($"角色已创建: {character.Name}");
                }
                catch (Exception saveEx)
                {
                    _logger.LogWarning(saveEx, $"保存角色失败，但继续执行: {character.Name}");
                }

                return character;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建角色失败: {plannedCharacter.Name}");
                return null;
            }
        }

        /// <summary>
        /// 使用AI生成详细的角色信息
        /// </summary>
        private async Task<DetailedCharacter> GenerateDetailedCharacterAsync(PlannedCharacter plannedCharacter, Models.ExecutionContext context)
        {
            try
            {
                var prompt = BuildDetailedCharacterPrompt(plannedCharacter, context);
                var aiResponse = await _aiService.GenerateTextAsync(prompt, 2000, 0.8f);

                // 解析AI响应生成详细角色信息
                return ParseDetailedCharacterResponse(aiResponse, plannedCharacter);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"AI生成角色详细信息失败: {plannedCharacter.Name}");

                // 返回基础角色信息作为后备
                return new DetailedCharacter
                {
                    Name = plannedCharacter.Name,
                    Description = plannedCharacter.Description,
                    Attributes = plannedCharacter.Attributes,
                    Skills = ConvertListToDictionary(plannedCharacter.Skills),
                    Equipment = ConvertListToDictionary(plannedCharacter.Equipment)
                };
            }
        }

        /// <summary>
        /// 构建详细角色生成提示
        /// </summary>
        private string BuildDetailedCharacterPrompt(PlannedCharacter plannedCharacter, Models.ExecutionContext context)
        {
            var projectContext = context.Plan?.UserIntent?.ProjectContext;

            return $@"请根据以下角色规划信息，生成详细的角色设定：

=== 基础信息 ===
角色名称：{plannedCharacter.Name}
基础描述：{plannedCharacter.Description}
角色类型：{plannedCharacter.Type}
重要程度：{plannedCharacter.Importance}

=== 项目背景 ===
项目类型：{projectContext?.ProjectType ?? "通用"}
项目主题：{GetProjectTheme(projectContext)}

=== 生成要求 ===
请生成以下详细信息：

1. **详细描述**：扩展角色的外貌、性格、背景故事（200-300字）

2. **属性设定**：
   - 基础属性（如实力等级、年龄、身份等）
   - 性格特征（至少5个关键词）
   - 能力特长（具体描述）

3. **技能列表**：
   - 主要技能（3-5个，包括熟练度）
   - 特殊能力（如有）
   - 成长潜力

4. **装备道具**：
   - 常用装备（武器、防具等）
   - 特殊物品
   - 珍贵收藏

5. **关系网络**：
   - 重要关系（家人、朋友、敌人）
   - 社会地位
   - 影响力范围

请按以下格式输出：

**详细描述**：
[详细描述内容]

**属性设定**：
- 实力等级：[等级]
- 年龄：[年龄]
- 身份：[身份]
- 性格：[性格特征1], [性格特征2], [性格特征3], [性格特征4], [性格特征5]

**技能列表**：
- [技能名称1]：[熟练度] - [技能描述]
- [技能名称2]：[熟练度] - [技能描述]
- [技能名称3]：[熟练度] - [技能描述]

**装备道具**：
- [装备名称1]：[装备描述]
- [装备名称2]：[装备描述]

**关系网络**：
- [关系类型1]：[人物名称] - [关系描述]
- [关系类型2]：[人物名称] - [关系描述]";
        }

        /// <summary>
        /// 建立角色关系
        /// </summary>

        /// <summary>
        /// 创建若干个默认基线角色（用于AI返回异常或解析失败时的兜底）
        /// </summary>
        private List<PlannedCharacter> CreateBaselineCharacters(EnhancedUserIntent intent, int count)
        {
            var list = new List<PlannedCharacter>();
            var names = new[] { "主角候选", "配角候选A", "配角候选B", "反派候选", "背景角色" };
            for (int i = 0; i < count; i++)
            {
                list.Add(new PlannedCharacter
                {
                    Name = i < names.Length ? names[i] : $"角色候选{i + 1}",
                    Description = $"基于用户需求（{intent.OriginalRequest}）的默认候选角色，请在后续步骤细化。",
                    Type = i == 0 ? CharacterType.Protagonist : (i == 3 ? CharacterType.Antagonist : CharacterType.Supporting),
                    Importance = i == 0 ? CharacterImportance.Primary : CharacterImportance.Secondary,
                    Attributes = new Dictionary<string, object>
                    {
                        ["定位"] = i == 0 ? "主角" : (i == 3 ? "反派" : "配角"),
                        ["初始状态"] = "待细化",
                        ["目标"] = "待定义"
                    },
                    Skills = new List<string> { "基础技能1", "基础技能2" },
                    Equipment = new List<string> { "基础装备" }
                });
            }
            return list;
        }

        /// </summary>
        private async Task EstablishCharacterRelationshipsAsync(
            List<CharacterRelationship> relationships,
            List<Character> characters,
            Models.ExecutionContext context)
        {
            foreach (var relationship in relationships)
            {
                try
                {
                    // 这里应该调用数据服务保存关系
                    _logger.LogInformation($"建立关系: {relationship.FromCharacterId} -> {relationship.ToCharacterId}");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "建立角色关系失败");
                }
            }
        }

        /// <summary>
        /// 设置角色发展轨迹
        /// </summary>
        private async Task SetupCharacterDevelopmentPathsAsync(
            List<CharacterDevelopmentPath> developmentPaths,
            List<Character> characters,
            Models.ExecutionContext context)
        {
            foreach (var path in developmentPaths)
            {
                try
                {
                    // 这里应该调用数据服务保存发展轨迹
                    _logger.LogInformation($"设置发展轨迹: {path.CharacterId}");
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "设置角色发展轨迹失败");
                }
            }
        }

        /// <summary>
        /// 解析通用规划响应
        /// </summary>
        private async Task ParseGeneralPlanningResponseAsync(CharacterPlan plan, string aiResponse, CharacterPlanningIntent intent)
        {
            try
            {
                _logger.LogInformation("开始解析AI生成的角色规划响应");

                // 尝试从AI响应中提取具体的角色信息
                var characters = ExtractCharactersFromResponse(aiResponse);

                if (characters.Any())
                {
                    _logger.LogInformation($"从AI响应中提取到 {characters.Count} 个角色");
                    plan.Characters.AddRange(characters);
                }
                else
                {
                    // 如果无法提取具体角色，创建基于AI响应的通用角色
                    _logger.LogWarning("无法从AI响应中提取具体角色，创建通用角色");
                    var generalCharacter = new PlannedCharacter
                    {
                        Name = "AI规划角色",
                        Description = aiResponse,
                        Type = CharacterType.Supporting,
                        Importance = CharacterImportance.Secondary
                    };
                    plan.Characters.Add(generalCharacter);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "解析AI角色规划响应失败");

                // 创建一个包含完整AI响应的角色作为后备
                var fallbackCharacter = new PlannedCharacter
                {
                    Name = "AI生成角色",
                    Description = aiResponse,
                    Type = CharacterType.Supporting,
                    Importance = CharacterImportance.Secondary
                };
                plan.Characters.Add(fallbackCharacter);
            }
        }

        /// <summary>
        /// 从AI响应中提取角色信息
        /// </summary>
        private List<PlannedCharacter> ExtractCharactersFromResponse(string aiResponse)
        {
            var characters = new List<PlannedCharacter>();

            try
            {
                // 尝试按段落分割，寻找角色描述
                var sections = aiResponse.Split(new[] { "\n\n", "**", "##" }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var section in sections)
                {
                    if (IsCharacterSection(section))
                    {
                        var character = ParseCharacterSection(section);
                        if (character != null)
                        {
                            characters.Add(character);
                        }
                    }
                }

                // 如果没有找到明确的角色段落，尝试创建基于整体描述的角色
                if (!characters.Any() && !string.IsNullOrWhiteSpace(aiResponse))
                {
                    var character = CreateCharacterFromDescription(aiResponse);
                    if (character != null)
                    {
                        characters.Add(character);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "提取角色信息时发生错误");
            }

            return characters;
        }

        /// <summary>
        /// 判断是否为角色描述段落
        /// </summary>
        private bool IsCharacterSection(string section)
        {
            var characterKeywords = new[] { "主角", "配角", "反派", "角色", "人物", "主人公", "女主", "男主" };
            return characterKeywords.Any(keyword => section.Contains(keyword, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 解析角色段落
        /// </summary>
        private PlannedCharacter? ParseCharacterSection(string section)
        {
            try
            {
                var lines = section.Split('\n', StringSplitOptions.RemoveEmptyEntries);
                var character = new PlannedCharacter();

                // 尝试从第一行提取角色名称
                var firstLine = lines.FirstOrDefault()?.Trim();
                if (!string.IsNullOrEmpty(firstLine))
                {
                    // 移除数字、星号、冒号等标记
                    var cleanName = Regex.Replace(firstLine, @"^\d+\.\s*\*?\*?|[：:].*$", "").Trim();
                    character.Name = string.IsNullOrEmpty(cleanName) ? "未命名角色" : cleanName;
                }

                // 设置描述为整个段落
                character.Description = section;

                // 根据内容判断角色类型
                if (section.Contains("主角") || section.Contains("主人公"))
                {
                    character.Type = CharacterType.Protagonist;
                    character.Importance = CharacterImportance.Primary;
                }
                else if (section.Contains("反派") || section.Contains("敌人"))
                {
                    character.Type = CharacterType.Antagonist;
                    character.Importance = CharacterImportance.Secondary;
                }
                else
                {
                    character.Type = CharacterType.Supporting;
                    character.Importance = CharacterImportance.Secondary;
                }

                return character;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "解析角色段落失败");
                return null;
            }
        }

        /// <summary>
        /// 从整体描述创建角色
        /// </summary>
        private PlannedCharacter? CreateCharacterFromDescription(string description)
        {
            try
            {
                return new PlannedCharacter
                {
                    Name = "AI规划角色",
                    Description = description,
                    Type = CharacterType.Supporting,
                    Importance = CharacterImportance.Secondary
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "从描述创建角色失败");
                return null;
            }
        }

        /// <summary>
        /// 解析AI响应生成详细角色信息
        /// </summary>
        private DetailedCharacter ParseDetailedCharacterResponse(string aiResponse, PlannedCharacter plannedCharacter)
        {
            try
            {
                var detailedCharacter = new DetailedCharacter
                {
                    Name = plannedCharacter.Name,
                    Description = plannedCharacter.Description,
                    Attributes = new Dictionary<string, object>(plannedCharacter.Attributes),
                    Skills = ConvertListToDictionary(plannedCharacter.Skills),
                    Equipment = ConvertListToDictionary(plannedCharacter.Equipment)
                };

                // 解析详细描述
                var descriptionMatch = Regex.Match(aiResponse, @"\*\*详细描述\*\*：\s*\n(.*?)(?=\n\*\*|$)", RegexOptions.Singleline);
                if (descriptionMatch.Success)
                {
                    detailedCharacter.Description = descriptionMatch.Groups[1].Value.Trim();
                }

                // 解析属性设定
                var attributesMatch = Regex.Match(aiResponse, @"\*\*属性设定\*\*：\s*\n(.*?)(?=\n\*\*|$)", RegexOptions.Singleline);
                if (attributesMatch.Success)
                {
                    var attributesText = attributesMatch.Groups[1].Value;
                    ParseAttributes(attributesText, detailedCharacter.Attributes);
                }

                // 解析技能列表
                var skillsMatch = Regex.Match(aiResponse, @"\*\*技能列表\*\*：\s*\n(.*?)(?=\n\*\*|$)", RegexOptions.Singleline);
                if (skillsMatch.Success)
                {
                    var skillsText = skillsMatch.Groups[1].Value;
                    ParseSkills(skillsText, detailedCharacter.Skills);
                }

                // 解析装备道具
                var equipmentMatch = Regex.Match(aiResponse, @"\*\*装备道具\*\*：\s*\n(.*?)(?=\n\*\*|$)", RegexOptions.Singleline);
                if (equipmentMatch.Success)
                {
                    var equipmentText = equipmentMatch.Groups[1].Value;
                    ParseEquipment(equipmentText, detailedCharacter.Equipment);
                }

                return detailedCharacter;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "解析AI角色响应失败");

                // 返回基础信息
                return new DetailedCharacter
                {
                    Name = plannedCharacter.Name,
                    Description = plannedCharacter.Description,
                    Attributes = plannedCharacter.Attributes,
                    Skills = ConvertListToDictionary(plannedCharacter.Skills),
                    Equipment = ConvertListToDictionary(plannedCharacter.Equipment)
                };
            }
        }

        /// <summary>
        /// 解析属性信息
        /// </summary>
        private void ParseAttributes(string attributesText, Dictionary<string, object> attributes)
        {
            var lines = attributesText.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            foreach (var line in lines)
            {
                var match = Regex.Match(line.Trim(), @"^-\s*([^：:]+)[：:]\s*(.+)$");
                if (match.Success)
                {
                    var key = match.Groups[1].Value.Trim();
                    var value = match.Groups[2].Value.Trim();
                    attributes[key] = value;
                }
            }
        }

        /// <summary>
        /// 解析技能信息
        /// </summary>
        private void ParseSkills(string skillsText, Dictionary<string, object> skills)
        {
            var lines = skillsText.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            foreach (var line in lines)
            {
                var match = Regex.Match(line.Trim(), @"^-\s*([^：:]+)[：:]\s*(.+)$");
                if (match.Success)
                {
                    var skillName = match.Groups[1].Value.Trim();
                    var skillDescription = match.Groups[2].Value.Trim();
                    skills[skillName] = skillDescription;
                }
            }
        }

        /// <summary>
        /// 解析装备信息
        /// </summary>
        private void ParseEquipment(string equipmentText, Dictionary<string, object> equipment)
        {
            var lines = equipmentText.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            foreach (var line in lines)
            {
                var match = Regex.Match(line.Trim(), @"^-\s*([^：:]+)[：:]\s*(.+)$");
                if (match.Success)
                {
                    var equipmentName = match.Groups[1].Value.Trim();
                    var equipmentDescription = match.Groups[2].Value.Trim();
                    equipment[equipmentName] = equipmentDescription;
                }
            }
        }

        /// <summary>
        /// 将字符串列表转换为字典
        /// </summary>
        private Dictionary<string, object> ConvertListToDictionary(List<string> list)
        {
            var dictionary = new Dictionary<string, object>();
            for (int i = 0; i < list.Count; i++)
            {
                dictionary[$"项目{i + 1}"] = list[i];
            }
            return dictionary;
        }

        /// <summary>
        /// 获取项目主题
        /// </summary>
        private string GetProjectTheme(ProjectContext? projectContext)
        {
            if (projectContext?.Properties != null && projectContext.Properties.TryGetValue("Theme", out var theme))
            {
                return theme.ToString() ?? "未指定";
            }
            return "未指定";
        }
    }

    /// <summary>
    /// 详细角色信息类
    /// </summary>
    public class DetailedCharacter
    {
        public string Name { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public Dictionary<string, object> Attributes { get; set; } = new();
        public Dictionary<string, object> Skills { get; set; } = new();
        public Dictionary<string, object> Equipment { get; set; } = new();
    }
}
